<template>
  <div class="delivery-container">
    <!-- 查询 -->
    <div class="search-container">
      <el-input
          v-model="searchQuery"
          placeholder="按订单号或客户姓名搜索"
          class="search-input"
          @keyup.enter="fetchOrders"
      ></el-input>
      <el-button
          @click="fetchOrders"
          type="primary"
          class="search-button"
      >
        查询
      </el-button>
    </div>

    <!-- 错误信息 -->
    <div v-if="errorMessage" class="error-message">{{ errorMessage }}</div>

    <!-- 外卖订单表格 -->
    <el-table
        :data="orders"
        class="order-table"
        header-cell-class-name="table-header"
    >
      <el-table-column
          label="序号"
          type="index"
          width="60px"
          align="center"
      ></el-table-column>
      <el-table-column
          prop="orderId"
          label="订单号"
          width="120px"
          align="center"
      ></el-table-column>
      <el-table-column
          prop="customerName"
          label="客户姓名"
          width="120px"
          align="center"
      ></el-table-column>
      <el-table-column
          prop="orderTime"
          label="订单时间"
          width="180px"
          align="center"
          :formatter="formatDateTime"
      ></el-table-column>
      <el-table-column
          prop="totalAmount"
          label="订单金额"
          width="120px"
          align="center"
      ></el-table-column>
      <el-table-column
          prop="status"
          label="配送状态"
          width="120px"
          align="center"
      ></el-table-column>
      <el-table-column label="操作" width="240px" align="center">
        <template #default="scope">
          <el-button
              type="primary"
              size="small"
              @click="showOrderDetails(scope.row.orderId)"
          >
            查看详情
          </el-button>
          <el-button
              type="success"
              size="small"
              @click="acceptOrder(scope.row.orderId)"
              v-if="scope.row.status === '待接单'"
          >
            接单
          </el-button>
          <el-button
              type="success"
              size="small"
              @click="updateDeliveryStatus(scope.row.orderId, '已完成')"
              v-if="scope.row.status === '已接单'"
          >
            配送完成
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
          background
          v-model:current-page="pageNum"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
          class="pagination"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';
;

const orders = ref([]);
const searchQuery = ref('');
const errorMessage = ref('');
const pageNum = ref(1);
const pageSize = ref(10);
const total = ref(0);

const formatDateTime = (row, column) => {
  if (!row[column.property]) return '';
  return new Date(row[column.property]).toLocaleString();
};

const fetchOrders = async () => {
  try {
    const response = await axios.post('/api/getDeliveryOrders', {
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      searchQuery: searchQuery.value,
    });
    orders.value = response.data.records || [];
    total.value = response.data.total || 0;
    errorMessage.value = '';
  } catch (error) {
    errorMessage.value = `获取外卖订单信息出错：${error.message}`;
  }
};

const showOrderDetails = (orderId) => {
  // 这里可以添加跳转到订单详情页面的逻辑
  console.log(`查看订单详情: ${orderId}`);
};

const acceptOrder = async (orderId) => {
  try {
    const response = await axios.post('/api/acceptOrder', {
      orderId,
    });
    if (response.data.success) {
      fetchOrders();
    } else {
      errorMessage.value = response.data.message;
    }
  } catch (error) {
    errorMessage.value = `接单失败：${error.message}`;
  }
};

const updateDeliveryStatus = async (orderId, status) => {
  try {
    const response = await axios.post('/api/updateDeliveryStatus', {
      orderId,
      status,
    });
    if (response.data.success) {
      fetchOrders();
    } else {
      errorMessage.value = response.data.message;
    }
  } catch (error) {
    errorMessage.value = `更新配送状态失败：${error.message}`;
  }
};

const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  fetchOrders();
};

const handlePageChange = (newPage) => {
  pageNum.value = newPage;
  fetchOrders();
};

onMounted(fetchOrders);
</script>

<style scoped>
.delivery-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.search-container {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.search-input {
  width: 200px;
  margin-right: 10px;
}

.search-button {
  margin-right: 20px;
}

.error-message {
  color: #f56c6c;
  margin-bottom: 20px;
  text-align: center;
}

.order-table {
  width: 100%;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.table-header {
  background-color: #f0f2f5;
  font-weight: bold;
  color: #333;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.pagination {
  width: 100%;
}
</style>